import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/pages/home/fence/model/fence_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

class FencePage extends ConsumerStatefulWidget {
  const FencePage({super.key});

  @override
  ConsumerState<FencePage> createState() => _FencePageState();
}

class _FencePageState extends ConsumerState<FencePage> {
  List<FenceData>? fenceList = [];

  _fetchFenceList() async {

    final deviceInfo = ref.watch(deviceInfoProvider);
    final queryParams = {
      'imei': deviceInfo.imei,
    };
    final res = await post<FenceListResp, FenceListResp>('/electronic-fence/list',
        data: queryParams, decodeType: FenceListResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        setState(() {
          fenceList = resp.data!;
        });

      } else {
        ToastUtils.showToast(resp.msg ?? '获取围栏列表失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast('获取围栏列表失败');
    });
  }

  Widget _buildList() {
    return ListView.builder(
        itemCount: fenceList?.length ?? 0,
        itemBuilder: (BuildContext context, int index) {
          final fence = fenceList?[index];
          final longitude = NumUtils.formatNum(fence?.longitude ?? 0, format: '0.000000');
          final latitude = NumUtils.formatNum(fence?.latitude ?? 0, format: '0.000000');
          final radius = NumUtils.formatNum(
            fence?.radius ?? 0,
          );
          return Slidable(
            endActionPane: ActionPane(
              motion: const ScrollMotion(),
              children: [
                CustomSlidableAction(
                  key: ValueKey(fence?.id),
                  onPressed: (context) async {
                    final deviceInfo = ref.read(deviceInfoProvider);
                    final queryParams = {
                      'imei': deviceInfo.imei,
                      'id': fence?.id,
                    };
                    final url = '/electronic-fence/${fence?.id}';
                    final res = await delete<BaseResp, BaseResp>(url, data: queryParams, decodeType: BaseResp());
                    res.when(success: (resp) {
                      if (resp.code == 200) {
                        ToastUtils.showToast('删除成功');
                        setState(() {
                          fenceList?.removeAt(index);
                        });
                      } else {
                        ToastUtils.showToast(resp.msg ?? '删除失败');
                      }
                    }, failure: (String msg, int code) {
                      ToastUtils.showToast('删除失败');
                    });
                  },
                  backgroundColor: Colors.transparent,
                  padding: const EdgeInsets.only(top: 20),
                  child: Container(
                    height: 60,
                    decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Center(
                      child: Text(
                        '删除',
                        style: TextStyle(
                          fontSize: 15,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            child: GestureDetector(
              onTap: () async {
                final result = await context.push<bool>(RouterManager.createFence, extra: fence);
                if (result == true) {
                  _fetchFenceList();
                }
              },
              child: Container(
                height: 60,
                margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Container(
                            margin: const EdgeInsets.only(left: 12),
                            child: Text(
                              '围栏名称：${fence?.name ?? ''}',
                              style: TextStyle(
                                fontSize: 17,
                                color: AppTheme.themeConfig.primaryTextColor,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: Container(
                            margin: const EdgeInsets.only(left: 12),
                            child: Text(
                              '经度: ${longitude} 纬度: ${latitude} 半径: ${radius}米',
                              style: TextStyle(
                                fontSize: 13,
                                color: AppTheme.themeConfig.infoTextColor,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  Widget _buildCreateButton() {
    return Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: ElevatedButton(
        onPressed: () async {
          XLogger.debug('创建围栏');
          // 创建围栏
          final refresh = await context.push<bool>(RouterManager.createFence);
          if (refresh == true) {
            _fetchFenceList();
          }
        },
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          backgroundColor: AppTheme.themeConfig.primaryColor,
        ),
        child: const Text(
          '创建围栏',
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fetchFenceList();
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            height: kToolbarHeight,
            padding: const EdgeInsets.only(top: 8),
            alignment: Alignment.center,
            child: const Text(' <返回',
                textAlign: TextAlign.center,
                maxLines: 1,
                style: TextStyle(color: Colors.black)),
          ),

        ),
        title: Text(
          "围栏",
          style: TextStyle(color: ColorUtils.hexToColor("#009FE8")),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.navBarColor,
        foregroundColor: Colors.black26,
        titleTextStyle: TextStyle(),
      ),
      backgroundColor: ColorUtils.hexToColor('#F5F5F5'),
      body: Stack(
        children: [
          _buildList(),
          _buildCreateButton(),
        ],
      ),
    );
  }
}
